import base64
from aip import AipFace
import requests
import json
import os

# 调用百度sdk 实现人脸的匹配

headers = {'content-type': 'application/json',
               'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0)\
                Gecko/20100101 Firefox/22.0'}

# 获取到access_token
# client_id 为官网获取的AK， client_secret 为官网获取的SK
def get_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=da8fDxAhr5TZo8Kz6FThNtmX&client_secret=dneXqMVh7xfV3f3OESkqZVpCU8g3AFnP'
    request = requests.post(url=host, headers=headers)
    token = json.loads(request.content)
    access_token = token['access_token']
    return access_token

# 初始化AipFace对象
# 定义常量
APP_ID = '10xxxxx'
API_KEY = 'da8fDxxxxxxxxxxxxxxxx'
SECRET_KEY = 'dneXqMVxxxxxxxxxxxxxxxx'
aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY)

# 返回文件夹下的图片列表
def get_img():
    imgs = []
    path = "Facebase/"
    files = os.listdir(path)
    for eachImg in files:
        filename = path + os.path.basename(eachImg)
        imgs.append(filename)
    return imgs

# 将照片逐个编码base64 返回字符串
def get_image(files):
    images = ''
    for file in files:
        handler = open(file, 'rb')
        image = handler.read()
        handler.close()
        if images != '':
            images += ','
        img = base64.b64encode(image)
        images = images + str(img, encoding='utf-8')
    return images

# 调用sdk 获得匹配指数
# 因为调用的工具是照片的一一对比，所以将要比对的照片命名为0，对索引为0的结果集合进行返回
def get_score(access_token, data):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v2/match" + "?access_token=" + access_token
    request = requests.post(url=request_url, data=data, headers=headers)
    response = json.loads(request.content)['result']
    for re in response:
        if (re['index_i'] == '0' or re['index_j'] == '0') and re['score'] > 80:
            return '存在匹配项\n相似度为：' + str(re['score'])
            # print('存在匹配项' + str(re['score']))
            # return
    return '无可匹配项'
    # print('无可匹配项')

def main():
    token = get_token()
    imgs = get_img()
    data = {
        'images': get_image(imgs)
    }
    score = get_score(token, data)
    return score

if __name__ == '__main__':
    main()